'use strict';
const {redis_set_dict_list} =  require('../../../utils/init')
const BaseController = require('../../core/base_controller');

class DictionaryController extends BaseController {

  async getAllDictList(){
    const { ctx } = this;
    const data = await ctx.model.Dictionary.findAll({
      where:{dict_type:'business'}
    })
    this.success(data);
  }
  async index() {
    const { ctx } = this;
    const { dict_type } = ctx.query;
    const where = {};
    if (dict_type) {
      where.dict_type = dict_type;
    }

    const list = await ctx.model.Dictionary.findAll({
      where,
      include: [{
        model: ctx.model.DictionaryDetail,
      }],
      order: [
        [ctx.model.DictionaryDetail, 'sort', 'ASC']
      ]
    });

    this.success(list);
  }

  async create() {
    const { ctx } = this;
    const rules = {
      dict_key: { type: 'string', required: true },
      dict_value: { type: 'string', required: true },
      dict_type: {
        type: 'enum',
        values: ['system','business'],
        required: true,
        message: '字典类型枚举值错误', },
      icon: { type: 'string', required: false },
      description: { type: 'string', required: false },
    };

    try {
      ctx.validate(rules);
    } catch (err) {
      ctx.throw(400, '参数错误');
    }

    const { dict_key, dict_type } = ctx.request.body;
    const exists = await ctx.model.Dictionary.findOne({
      where: { dict_key, dict_type }
    });

    if (exists) {
      ctx.throw(400, '该字典键已存在');
    }

    const dictionary = await ctx.model.Dictionary.create(ctx.request.body);
    redis_set_dict_list(ctx.app)
    this.success(dictionary);
  }

  async update() {
    const { ctx } = this;
    const id = ctx.params.id;
    const dictionary = await ctx.model.Dictionary.findByPk(id);

    if (!dictionary) {
      ctx.throw(404, '字典不存在');
    }

    const { dict_key, dict_type } = ctx.request.body;
    const exists = await ctx.model.Dictionary.findOne({
      where: {
        dict_key,
        dict_type,
        id: { [ctx.model.Sequelize.Op.ne]: id }
      }
    });

    if (exists) {
      ctx.throw(400, '该字典键已存在');
    }

    await dictionary.update(ctx.request.body);
    redis_set_dict_list(ctx.app)
    this.success(dictionary);
  }

  async destroy() {
    const { ctx } = this;
    const dictionary = await ctx.model.Dictionary.findByPk(ctx.params.id);

    if (!dictionary) {
      ctx.throw(404, '字典不存在');
    }

    await dictionary.destroy();
    redis_set_dict_list(ctx.app)
    this.success(null, '删除成功');
  }
}

module.exports = DictionaryController;
